package cn.com.nes.site.service.contract.impl;

import cn.com.nes.common.util.id.IdUtils;
import cn.com.nes.mybatis.agent.contract.entity.ContractInfo;
import cn.com.nes.mybatis.agent.contract.mapper.ContractInfoMapper;
import cn.com.nes.mybatis.agent.system.entity.TParam;
import cn.com.nes.site.service.contract.ContractBusinessService;
import cn.com.nes.site.service.contract.ContractTypeService;
import cn.com.nes.site.service.contract.bo.ContractBO;
import cn.com.nes.site.service.contract.bo.ContractSaveBO;
import cn.com.nes.site.service.contract.dto.ContractDTO;
import cn.com.nes.site.service.contract.dto.ContractTypeDTO;
import cn.com.nes.site.service.system.dict.TParamService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ContractBusinessServiceImpl extends ServiceImpl<ContractInfoMapper, ContractInfo> implements ContractBusinessService {

    @Resource
    private ContractTypeService contractTypeService;

    @Resource
    private TParamService tParamService;

    /**
     * 合同分页查询
     * @param contractBO
     * @return
     */
    @Override
    public Page<ContractDTO> getContractPage(ContractBO contractBO) throws Exception {
        Page<ContractDTO> page = new Page<>(contractBO.getPageid(), contractBO.getPagesize());
        List<ContractDTO> contractDTOList = this.baseMapper.getContractPage(page, contractBO);

        List<ContractTypeDTO> contractTypeList = contractTypeService.getContractTypesByCompanyId(contractBO.getOperateUserCompanyId());
        Map<Integer, ContractTypeDTO> contractTypeDTOMap = contractTypeList.stream()
                .collect(Collectors.toMap(ContractTypeDTO::getTypeCode, contractTypeDTO -> contractTypeDTO));

        // 合同审核状态字典
        Map<String, TParam> auditStateMap = tParamService.getMapValueIsKey("87");
        // 合同状态字典
        Map<String, TParam> contractStatusMap = tParamService.getMapValueIsKey("401");

        for (ContractDTO contractDTO : contractDTOList) {
            contractDTO.setContractTypeName(contractTypeDTOMap.get(contractDTO.getContractType()).getTypeName());
            contractDTO.setContractAuditStatusName(auditStateMap.get(String.valueOf(contractDTO.getContractAuditStatus())).getName());
            contractDTO.setContractStatus(judgeContractStatus(contractDTO));
            contractDTO.setContractStatusName(contractStatusMap.get(String.valueOf(contractDTO.getContractStatus())).getName());
        }
        page.setRecords(contractDTOList);
        return page;
    }

    @NotNull
    private static Integer judgeContractStatus(ContractDTO contractDTO) {
        Integer contractStatus = 0;
        if (contractDTO.getTerminated() == 1) {
            contractStatus = 3;
        } else {
            Date effectiveDate = contractDTO.getEffectiveDate();
            Date terminationDate = contractDTO.getTerminationDate();
            final long now = System.currentTimeMillis();
            if (effectiveDate != null && terminationDate != null) {
                if (effectiveDate.getTime() > now) {
                    contractStatus = 0;
                } else if (terminationDate.getTime() > now) {
                    contractStatus = 1;
                } else {
                    contractStatus = 2;
                }
            } else if (effectiveDate != null) {
                contractStatus = effectiveDate.getTime() > now ? 0 : 1;
            } else if (terminationDate != null) {
                contractStatus = terminationDate.getTime() > now ? 1 : 2;
            } else {
                contractStatus = 1;
            }
        }
        return contractStatus;
    }

    /**
     * 合同保存
     * @param contractSaveBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ContractDTO saveContract(ContractSaveBO contractSaveBO) throws Exception {
        ContractInfo contractInfo = new ContractInfo();
        if (ObjectUtil.isEmpty(contractSaveBO.getContractUuid())) {
            contractInfo.setId(IdUtils.uuid());
            contractInfo.setCreatorId(contractSaveBO.getOperateUserId());
            contractInfo.setGmtCreate(contractSaveBO.getOperateDate());
            contractInfo.setGmtModifiedId(contractSaveBO.getOperateUserId());
            contractInfo.setGmtModified(contractSaveBO.getOperateDate());
            contractInfo.setContractNumber(contractSaveBO.getContractNumber());
        } else {
            contractInfo = this.baseMapper.selectById(contractSaveBO.getContractUuid());
            contractInfo.setId(contractSaveBO.getContractUuid());
            contractInfo.setGmtModifiedId(contractSaveBO.getOperateUserId());
            contractInfo.setGmtModified(contractSaveBO.getOperateDate());
        }
        contractInfo.setType(contractSaveBO.getContractType());
        contractInfo.setName(contractSaveBO.getContractName());
        contractInfo.setCompanyId(contractSaveBO.getOperateUserCompanyId());
        contractInfo.setCustomerId(contractSaveBO.getCustomerUuid());
        contractInfo.setCustomerName(contractSaveBO.getCustomerName());
        contractInfo.setContractAmount(contractSaveBO.getContractAmount());
        contractInfo.setEffectiveDate(contractSaveBO.getEffectiveDate());
        contractInfo.setTerminationDate(contractSaveBO.getTerminationDate());
        contractInfo.setFileName(contractSaveBO.getFileName());
        contractInfo.setOssPath(contractSaveBO.getOssPath());
        contractInfo.setSaleOderId(contractSaveBO.getSaleOderId());

        this.saveOrUpdate(contractInfo);
        return new ContractDTO(contractInfo.getId());
    }


}
